package com.newflypig.jblog.dao.hibernate;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.exception.ConstraintViolationException;
import org.springframework.stereotype.Repository;

import com.newflypig.jblog.dao.IArchiveDAO;
import com.newflypig.jblog.model.Archive;

@Repository("archiveDao")
public class ArchiveDAOImpl extends BaseHibernateDAO<Archive> implements IArchiveDAO {
	
	/**
	 * Archive是不可更新视图，向其中添加Archive需要更新原始表:jblog_archive_t
	 * 重写DAO中的save函数，使用原生SQL向原始表添加数据
	 * 因为title做了unique key，所以这里需要捕获一个ConstraintViolationException异常
	 * 为了方便此后的过程继续使用archive以及其id，在插入数据后，查询一遍数据库，将其ID返回
	 */
	@SuppressWarnings( "unchecked" )
	@Override
	public Serializable save(Archive archive) {
		String sql = "insert into jblog_archive_t(title) values(:title)";
		Query query = this.getSession().createSQLQuery(sql).setString("title", archive.getTitle());
		try{
			query.executeUpdate();
		}catch(ConstraintViolationException e){
			System.out.println("Duplicate entry '" + archive.getTitle() + "' for key 'title_UNIQUE' so ignored");
		}
		
		sql = "select id from jblog_archive_t where title = :title";
		query = this.getSession().createSQLQuery(sql).setString("title", archive.getTitle());
		Integer id = (Integer)(((List<Object>)query.list()).get(0));
		archive.setArchiveId(id);
		
		return archive.getArchiveId();
	}

	@Override
	public void clearAll() {		
		String[] sqlList = {"update jblog_article set archive_id = null",
							"SET FOREIGN_KEY_CHECKS=0",
							"truncate table jblog_archive_t",
							"SET FOREIGN_KEY_CHECKS=1"};
		try{
			for(String sql : sqlList){
				Query query = this.getSession().createSQLQuery(sql);
				query.executeUpdate();
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}
